// pages/personalKeyInformation/index.js
import DB from '../../utils/db';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    form: {
      userText: '',
      postText: '',
      genderText: '',
      birthText: '',
      cityText: '',
      workText: '',
      educationText: '',
      phone: '',
      email: '',
      openId: '',
      img: ''
    },
    count: 0,
    mode: '',
    // dateVisible: false,
    birth: new Date('2000-01-01').getTime(), // 支持时间戳传入
    // 指定选择区间起始值
    start: '1950-01-01 00:00:00',
    end: '2030-09-09 12:12:12',
    genderValue: [],
    gender: [
      { label: '男', value: '男' },
      { label: '女', value: '女' },
    ],
    workValue: [],
    work: [
      { label: '1年以下', value: '1年以下' },
      { label: '1-3年', value: '1-3年' },
      { label: '3-5年', value: '3-5年' },
      { label: '5-10年', value: '5-10年' },
      { label: '10年以上', value: '10年以上' },
    ],
    educationValue: [],
    education: [
      { label: '专科', value: '专科' },
      { label: '本科', value: '本科' },
      { label: '硕士', value: '硕士' },
      { label: '博士', value: '博士' },
    ],
    phoneError: false,
    emailError: false,
    fileList: [],
    gridConfig: {
      column: 4,
      width: 160,
      height: 160,
    },
    file: '',

  },



  onGenderPicker() {
    this.setData({ genderVisible: true });
  },

  onWorkPicker() {
    this.setData({ workVisible: true });
  },
  onEducationPicker() {
    this.setData({ educationVisible: true });
  },


  onPhoneInput(e) {
    const { phoneError } = this.data;
    const isPhoneNumber = /^[1][3,4,5,7,8,9][0-9]{9}$/.test(e.detail.value);
    if (phoneError === isPhoneNumber) {
      this.setData({
        phoneError: !isPhoneNumber,
        'form.phone': e.detail.value
      });
    }
  },

  onEmailInput(e) {
    this.setData({
      'form.email': e.detail.value
    });
  },

  onPickerChange(e) {
    const { key } = e.currentTarget.dataset;
    const { value } = e.detail;

    console.log('picker change:', e.detail);
    this.setData({
      [`${key}Visible`]: false,
      [`${key}Value`]: value,
      [`form.${key}Text`]: value.join(' '),
    });
  },

  onPickerCancel(e) {
    const { key } = e.currentTarget.dataset;
    console.log(e, '取消');
    console.log('picker1 cancel:');
    this.setData({
      [`${key}Visible`]: false,
    });
  },

  showPicker(e) {
    const { mode } = e.currentTarget.dataset;
    this.setData({
      mode,
      [`${mode}Visible`]: true,
    });
  },

  hidePicker() {
    const { mode } = this.data;
    this.setData({
      [`${mode}Visible`]: false,
    });
  },
  onConfirm(e) {
    const { value } = e.detail;
    const { mode } = this.data;

    console.log('confirm', value);

    this.setData({
      [mode]: value,
      [`form.${mode}Text`]: value,
    });

    this.hidePicker();
  },

  onColumnChange(e) {
    console.log('pick', e.detail.value);
  },

  onUserTextInput(e) {
    // console.log(e.detail.value)
    this.setData({
      'form.userText': e.detail.value
    })
  },


  onPostTextInput(e) {
    // console.log(e.detail.value)
    this.setData({
      'form.postText': e.detail.value
    })
  },

  onCityTextInput(e) {
    // console.log(e.detail.value)
    this.setData({
      'form.cityText': e.detail.value
    })
  },

  addPersonalKeyInformation() {
    // console.log(this.data.form)
    this.data.form.openId = this.data.openId
    wx.showLoading({
      title: '保存中',
    })
    if (this.data.file != '') {
      wx.cloud.uploadFile({
        // 指定上传到的云路径
        cloudPath: `profile-picture/${this.data.openId}.jpg`,
        // 指定要上传的文件的小程序临时文件路径
        filePath: this.data.file,
      }).then(res => {
        this.setData({
          haveGetImgSrc: true,
          'form.img': res.fileID
        });
        DB.add('addPersonalKeyInformation', this.data.form).then(() => {
          wx.hideLoading();
          wx.reLaunch({
            url: `/pages/createResume/index`,
          });
        }).catch(() => {
          wx.hideLoading();
          wx.showToast({
            title: '添加失败',
            icon: 'error',
            duration: 2000
          });
        });
      }).catch((e) => {
      });
    } else {
      DB.add('addPersonalKeyInformation', this.data.form).then(() => {
        wx.hideLoading();
        wx.reLaunch({
          url: `/pages/createResume/index`,
        });
      }).catch(() => {
        wx.hideLoading();
        wx.showToast({
          title: '添加失败',
          icon: 'error',
          duration: 2000
        });
      });
    }

  },

  updatePersonalKeyInformation() {
    console.log(this.data.form)
    wx.showLoading({
      title: '保存中',
    })
    if (this.data.file != '') {
      wx.cloud.uploadFile({
        // 指定上传到的云路径
        cloudPath: `profile-picture/${this.data.openId}.jpg`,
        // 指定要上传的文件的小程序临时文件路径
        filePath: this.data.file,
      }).then(res => {
        this.setData({
          haveGetImgSrc: true,
          'form.img': res.fileID
        });
        DB.update('updatePersonalKeyInformation', this.data.form).then(() => {
          wx.hideLoading();
          wx.reLaunch({
            url: `/pages/createResume/index`,
          });
        }).catch(() => {
          wx.hideLoading();
          wx.showToast({
            title: '更新失败',
            icon: 'error',
            duration: 2000
          });
        });
      }).catch((e) => {
      });
    } else {
      DB.update('updatePersonalKeyInformation', this.data.form).then(() => {
        wx.hideLoading();
        wx.reLaunch({
          url: `/pages/createResume/index`,
        });
      }).catch(() => {
        wx.hideLoading();
        wx.showToast({
          title: '更新失败',
          icon: 'error',
          duration: 2000
        });
      });
    }
  },

  selectPersonalKeyInformation(id) {
    // console.log(this.data.openId)
    DB.select('selectPersonalKeyInformation', id).then((resp) => {

      this.setData({
        form: resp.result.data,
        count: 1,
        fileList: [...this.data.fileList, ...[{ url: resp.result.data.img }]], // 此时设置了 fileList 之后才会展示选择的图片
      });
      wx.hideLoading();
    }).catch(() => {
      console.log(e);
      this.setData({
        showUploadTip: true
      });
      wx.hideLoading();
    });
  },

  handleAdd(e) {
    const { fileList } = this.data;
    const { files } = e.detail;
    console.log(e.detail)

    // 方法1：选择完所有图片之后，统一上传，因此选择完就直接展示
    this.setData({
      fileList: [...fileList, ...files], // 此时设置了 fileList 之后才会展示选择的图片
    });
    // this.onUpload()

    // 方法2：每次选择图片都上传，展示每次上传图片的进度
    // files.forEach(file => this.onUpload(file))
    // 获取图片原始信息
    // console.log(this.data.fileList[0].url)
    wx.getImageInfo({
      src: this.data.fileList[0].url,
      success: (res) => {
        const { width, height } = res;
        const targetWidth = 215; // 目标宽度
        const targetHeight = 300; // 目标高度

        // 创建离屏 Canvas 进行缩放
        this.scaleImage(this.data.fileList[0].url, width, height, targetWidth, targetHeight);
      },
      fail: (err) => {
        wx.showToast({ title: '图片读取失败', icon: 'none' });
      },
    });
  },

  // 使用 Canvas 缩放图片
  scaleImage(src, originalWidth, originalHeight, targetWidth, targetHeight) {
    const canvasId = 'resize-canvas';
    const ctx = wx.createCanvasContext(canvasId);

    // 计算缩放比例（保持宽高比）
    const scale = Math.min(
      targetWidth / originalWidth,
      targetHeight / originalHeight
    );

    // 绘制缩放后的图片
    ctx.drawImage(
      src,
      0, 0, originalWidth, originalHeight, // 原始尺寸
      0, 0, targetWidth, targetHeight      // 目标尺寸
    );

    ctx.draw(false, () => {
      // 导出缩放后的图片
      wx.canvasToTempFilePath({
        canvasId,
        success: (res) => {
          console.log("res.tempFilePath:" + res.tempFilePath)
          // callback(res.tempFilePath); // 返回新路径
          this.setData({ file: res.tempFilePath });
        },

      });
    });
  },
  onUpload(file) {
    console.log(file)
    wx.showLoading({
      title: '上传中',
    })
    wx.cloud.uploadFile({
      // 指定上传到的云路径
      cloudPath: `profile-picture/${this.data.openId}.jpg`,
      // 指定要上传的文件的小程序临时文件路径
      filePath: file,
    }).then(res => {
      this.setData({
        haveGetImgSrc: true,
        'form.img': res.fileID
      });
      wx.hideLoading();
    }).catch((e) => {
      wx.hideLoading();
    });

  },
  handleRemove(e) {
    const { index } = e.detail;
    const { fileList } = this.data;

    fileList.splice(index, 1);
    this.setData({
      fileList,
    });
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      'openId': wx.getStorageSync("openId")
    })
    if (options.id != 'undefined') {
      wx.showLoading({
        title: '数据加载中...', // 这里设置提示词
        mask: true // 显示透明蒙层
      });
      this.selectPersonalKeyInformation(options.id)
    }
    // console.log(options.id)
    // this.selectPersonalKeyInformation()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.data.form.openId = this.data.openId
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage() {

  // }
})